<?php
/**
 * Author: Nguyen Hoai Tan (nguoiao007@gmail.com)
 * 
 * @category   default 
 * @copyright  Copyright (c) 2009 visualidea.org
 * @license    http://license.visualidea.org
 * @version    v 1.0 2009-04-15
 * 
 */
require_once 'modules/product/models/Product.php';
require_once 'modules/product/models/Input.php';
require_once 'modules/product/models/Sale.php';
require_once 'modules/product/models/Unit.php';
class product_AdminController extends Nine_Controller_Action_Admin 
{
    
    public function manageProductAction()
    {
        $objProduct = new Models_Product();
        
        /**
         * Check permission
         */
        if (false == $this->checkPermission('see_product', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
//        echo "<pre>";print_r($_POST);die;
        $this->view->headTitle('Quản lý sản phẩm');
        $this->view->menu = array('product', 'manageproduct');
        
        
        $config = Nine_Registry::getConfig();
        $numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page",1);
        $displayNum = $this->_getParam('displayNum', false);
        $objProduct = new Models_Product();
        $errors = array();
        
        /*
         * add input
         */
        $input = $this->_getParam('input', false);  
        $isInput = $this->_getParam('isInput', '1');
        $objInput = new Models_Input();
        $objSale  = new Models_Sale();
        
        
        if (false != $input && $input['soluong'] > 0 ) {
        	if ('1' == $isInput) {
        		/**
        		 * Input
        		 */
        		if (null == $input['created_date']) {
	                unset($input['created_date']);
	            } else {
	                $tmp = explode('/', $input['created_date']);
	                $input['created_date'] = mktime(0, 0, 0, $tmp[1], $tmp[0], $tmp[2]);
	            }
	            
        				$product = $objProduct->getProductById($input['product_id']);
        				$objInput->insert($input);
        				
        				$newProduct = array();        				
        				$newProduct['store'] = $product['store'] + $input['soluong'];
        				$newProduct['update'] = time(); 
		                $objProduct->update($newProduct, array('product_id =?' =>  $input['product_id']));
		                $this->session->productMessage =  array(
                           'success' => true,
                           'message' => 'Thông tin nhập hàng đã được cập nhật.'
                        );
                        $this->_redirect('product/admin/manage-product');
                        
        	} else {
        		/**
        		 * Sale
        		 */
        		if (null == $input['created_date']) {
	                unset($input['created_date']);
	            } else {
	                $tmp = explode('/', $input['created_date']);
	                $input['created_date'] = mktime(0, 0, 0, $tmp[1], $tmp[0], $tmp[2]);
	            }
        				$product = $objProduct->getProductById($input['product_id']);
        				$objSale->insert($input);
        				
        				$newProduct = array();        				
        				$newProduct['store'] = $product['store'] - $input['soluong'];
        				$newProduct['update'] = time(); 
		                $objProduct->update($newProduct, array('product_id =?' =>  $input['product_id']));
		                $this->session->productMessage =  array(
                           'success' => true,
                           'message' => 'Thông tin xuất hàng đã được cập nhật.'
                        );
                      $this->_redirect('product/admin/manage-product');
        	}
        }
        
        
        /**
         * Update sorting
         */
        $data = $this->_getParam('data', array());
        
        /**
         * Get number of items per page
         */
        if (false === $displayNum) {
            $displayNum = $this->session->productDisplayNum;
        } else {
            $this->session->productDisplayNum = $displayNum;
        }
        if (null != $displayNum) {
            $numRowPerPage = $displayNum;
        }
        /**
         * Get condition
         */
        $condition = $this->_getParam('condition', false);
        if (false === $condition) {
            $condition = array();
        } else {
            $this->session->productCondition = $condition;
            $currentPage = 1;
        }
        if (false == $condition) {
            $condition = array();
        }
        
        
        /**
         * Get all products
         */
        
        $allProduct = $objProduct->getAllProducts($condition, array('product_id DESC','update DESC'),
                                                   $numRowPerPage,
                                                   ($currentPage - 1) * $numRowPerPage
                                                  );
        /**
         * Count all products
         */
        $count = count($objProduct->getAllProducts($condition));
        /**
         * Format
         */
        foreach ($allProduct as $index=> &$product) {
            /**
             * Change date
             */
            if (0 != $product['created_date']) {
                $product['created_date'] = date($config['dateFormat'], $product['created_date']);
            } else {
                $product['created_date'] = '';
            }
            
//            if($product['unit']){
//            	$objUnit = new Models_Unit();
//            	$con['unit_id'] = $product['unit'];
//                $unit = 	$objUnit->getUnitById($product['unit']);
//                
////                echo "<pre>";print_r($unit);die;
//            	$product['unit'] = $unit['name'];
////            	echo "<pre>";print_r($product);die;
//            }
        }
        unset($product);
//        echo "<pre>";print_r($allProduct);die;
        /**
         * Prepare for template
         */
        $date = time();
        $date = date('d/m/Y', $date);
        
        $this->view->date = $date;
        
        /**
         * Set values for tempalte
         */
        $this->setPagination($numRowPerPage, $currentPage, $count);
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
        $this->view->allProduct = $allProduct;
        $this->view->productMessage = $this->session->productMessage;
        $this->session->productMessage = null;
        $this->view->condition = $condition;
        $this->view->displayNum = $numRowPerPage;
        $this->view->fullPermisison = $this->checkPermission('see_product');
    }
    
     public function searchProductAction()
    {
        $objProduct = new Models_Product();
        
        /**
         * Check permission
         */
        if (false == $this->checkPermission('search_product', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
//        echo "<pre>";print_r($_POST);die;
        $this->view->headTitle('Thống kê giao dịch');
        $this->view->menu = array('product', 'searchproduct');
        
        
        $config = Nine_Registry::getConfig();
        $numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page",1);
        $displayNum = $this->_getParam('displayNum', false);
        
        $objProduct = new Models_Product();
        $errors = array();
        
        
        /**
         * Update sorting
         */
        $data = $this->_getParam('data', array());
        
        /**
         * Get number of items per page
         */
        if (false === $displayNum) {
            $displayNum = $this->session->productDisplayNum;
        } else {
            $this->session->productDisplayNum = $displayNum;
        }
        if (null != $displayNum) {
            $numRowPerPage = $displayNum;
        }
        /**
         * Get condition
         */
        $condition = $this->_getParam('condition', false);
        if (false === $condition) {
            $condition = $this->session->productCondition;
        } else {
            $this->session->productCondition = $condition;
            $currentPage = 1;
        }
        if (false == $condition) {
            $condition = array();
        }
        
        
//        $allProduct = $objProduct->getAllProducts($condition, array('product_id DESC','update DESC'),
//                                                   $numRowPerPage,
//                                                   ($currentPage - 1) * $numRowPerPage
//                                                  );
        /**
         * Count all products
         */
        $count = count($objProduct->getAllProducts($condition));

        /**
         * Format
         */
//        foreach ($allProduct as $index=> &$product) {
//            /**
//             * Change date
//             */
//            if (0 != $product['created_date']) {
//                $product['created_date'] = date($config['dateFormat'], $product['created_date']);
//            } else {
//                $product['created_date'] = '';
//            }
//            
//            if($product['unit']){
//                $objUnit = new Models_Unit();
//                $con['unit_id'] = $product['unit'];
//                $unit =     $objUnit->getUnitById($product['unit']);
//                
////                echo "<pre>";print_r($unit);die;
//                $product['unit'] = $unit['name'];
////              echo "<pre>";print_r($product);die;
//            }
//        }
//        unset($product);
        
        $objInput = new Models_Input();
        
        $allInput = $objInput->getAllInputs($condition, array('created_date DESC'));
//        echo "<pre>";print_r($allInput);die;
        $objUnit = new Models_Unit();
        
        $objSale = new Models_Sale();
        $allSale = $objSale->getAllSales($condition,array('created_date DESC'));
//        echo "<pre>";print_r($allSale);die;
        foreach ($allInput as &$item) {
            if (0 != $item['created_date']) {
                $item['created_date'] = date($config['dateFormat'], $item['created_date']);
            } else {
                $item['created_date'] = '';
            }
            $product =  $objProduct->getProductById($item['product_id']);
            if (false == $product) {
            	/**
            	 * There is no product now
            	 */
            	continue;
            }
            $item['product_name'] = $product['title'];
            $item['provider'] = $product['provider'];
            $con['unit_id'] = $product['unit'];

           	/**
           	 * Emtpy unit?
           	 */
            if (null == @$product['unit']) {
            	$item['unit'] = null;
            } else {
	            $unit =     $objUnit->getUnitById($product['unit']);
	            $item['unit'] =  $unit['name'];
            }
        }
        unset($item);
        
//        echo "<pre>";print_r($allInput);die;
        
        foreach ($allSale as &$sale) {
            if (0 != $sale['created_date']) {
                $sale['created_date'] = date($config['dateFormat'], $sale['created_date']);
            } else {
                $sale['created_date'] = '';
            }
            
            $product =  $objProduct->getProductById($sale['product_id']);
            if (false == $product) {
            	/**
            	 * There is no product now
            	 */
            	continue;
            }
//            echo "<pre>";print_r($product);die;
            $sale['product_name'] = $product['title'];
            $sale['provider'] = $product['provider'];
            $con['unit_id'] = $product['unit'];
            
           

           	/**
           	 * Emtpy unit?
           	 */
            if (null == @$product['unit']) {
            	$sale['unit']= null;
            } else { 
	            $unit =     $objUnit->getUnitById($product['unit']);
	            $sale['unit'] =  $unit['name'];
            }
            
        }
        unset($sale);
//        echo "<pre>";print_r($allSale);die;
		$total = 0;
		$totalGiaBan = 0;
        foreach ($allInput as $item ) {
        	$total = $total + ($item['input_price'] * $item['soluong']);
        	$totalGiaBan = $totalGiaBan + ($item['lsale_price'] * $item['soluong']);
        }
    	$totalInSale = 0;
		$totalOuSale = 0;
        foreach ($allSale as $item1 ) {
        	$totalInSale = $totalInSale + ($item1['sale_price'] * $item1['soluong']);
        	$totalOuSale = $totalOuSale + ($item1['lsale_price'] * $item1['soluong']);
        }
        
        $this->view->allInputs = $allInput;
        $this->view->allSales = $allSale;
        
        $this->view->total = number_format($total,0,',', ' ');
        $this->view->totalGiaBan = number_format($totalGiaBan,0,',', ' ');
        $this->view->totalInSale = number_format($totalInSale,0,',', ' ');
        $this->view->totalOuSale = number_format($totalOuSale,0,',', ' ');
        
        /**
         * Prepare for template
         */
        $date = time();
        $date = date('d/m/Y', $date);
        
        $this->view->date = $date;
        
        /**
         * Set values for tempalte
         */
        $this->setPagination($numRowPerPage, $currentPage, $count);
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
        $this->view->productMessage = $this->session->productMessage;
        $this->session->productMessage = null;
        $this->view->condition = $condition;
        $this->view->displayNum = $numRowPerPage;
        $this->view->fullPermisison = $this->checkPermission('see_product');
    }
    
    
    public function selectAction()
    {
        $objProduct = new Models_Product();
        
        /**
         * Check permission
         */
        if (false == $this->checkPermission('see_select', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $this->view->headTitle('Chi tiết sản phẩm');
        $this->setLayout('admin_1column');
        $this->view->menu = array('product', 'select');
        
        
        $config = Nine_Registry::getConfig();
        $numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page",1);
        $displayNum = $this->_getParam('displayNum', false);
        
        $id     = $this->_getParam('id', false);
        
        $objInput = new Models_Input();
        $objUnit = new Models_Unit();
        
        $objSale = new Models_Sale();
        
        
         /**
         * Check permission
         */
        if (false == $this->checkPermission('edit_sale', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $sale     = $this->_getParam('sale', false);

        if (false !== $sale) {
//            echo "<pre>";print_r($sale);die;
            foreach ($sale as $key => $item) {
                    if($item['soluong']||$item['sale_price']){
                        if (null == $item['created_date']) {
                            unset($item['created_date']);
                        } else {
                            $tmp = explode('/', $item['created_date']);
                            $item['created_date'] = mktime(0, 0, 0, $tmp[1], $tmp[0], $tmp[2]);
                        }
                        
                        
                        $editSale = $objSale->getSaleById($key); 
                        $item['product_id'] = $editSale['product_id'];
                        $newSale = $item;    
//                        echo "<pre>";print_r($editSale);die;                    
                        $product = $objProduct->getProductById($editSale['product_id']);
                        $product['update'] = $newSale['created_date'];
                        $objSale->update($newSale, array('sale_id=?' => $key));
                        if($newSale['soluong']){
                            
                            $product['store'] = $product['store'] - $editSale['soluong'] + $newSale['soluong'];
                            $objProduct->update($product, array('product_id=?'=> $product['product_id']));
                        }
                        
                         $this->session->selectMessage =  array(
                           'success' => true,
                           'message' => 'Thông tin xuất hàng đã được chỉnh sửa.'
                        );
                    }
                    
                }
            
                
        }
        
        /*
         * end sale
         */
        
        $allInput = $objInput->getAllByProductId(array('product_id'=> $id));
        
        $allSale = $objSale->getAllByProductId(array('product_id'=> $id));
        foreach ($allInput as &$item) {
            if (0 != $item['created_date']) {
                $item['created_date'] = date($config['dateFormat'], $item['created_date']);
            } else {
                $item['created_date'] = '';
            }
//            echo "<pre>";print_r($item);die;
        }
        unset($item);
//        echo "<pre>";print_r($allInput);die;
        
        foreach ($allSale as &$sale) {
            if (0 != $sale['created_date']) {
                $sale['created_date'] = date($config['dateFormat'], $sale['created_date']);
            } else {
                $sale['created_date'] = '';
            }
        }
        unset($sale);
        
        
        
        /**
         * Get all products
         */
        $product = $objProduct->getProductById($id);
            /**
             * Change date
             */
            if (0 != $product['created_date']) {
                $product['created_date'] = date($config['dateFormat'], $product['created_date']);
            } else {
                $product['created_date'] = '';
            }
            
//            if(@$product['unit']){
//                $objUnit = new Models_Unit();
//                $con['unit_id'] = $product['unit'];
//                $unit =     $objUnit->getAllById($con);
//                $product['unit'] = $unit[0]['name'];
//            }
            
            
            
        
        
        /**
         * Set values for tempalte
         */
        $this->view->product = $product;
        $this->view->allInputs= $allInput;
        $this->view->allSales = $allSale;
        $this->view->selectMessage = $this->session->selectMessage;
        $this->session->selectMessage = null;
        $this->view->displayNum = $numRowPerPage;
        $this->view->fullPermisison = $this->checkPermission('see_product');
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
    }
    
public function editSaleAction()
    {
        $objSale = new Models_Sale();
       $id     = $this->_getParam('id', false);     
//       echo "<pre>";print_r($id);die;
        
        if (false == $id) {
            $this->_redirect('product/admin/manage-product');
        }
        /**
         * Check permission
         */
//        $input = $objInput->getInputById($id);
        if (false == $this->checkPermission('edit_sale', null, '*'))
        {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        
        $salePost = $this->_getParam('sale', false);
        $objProduct = new Models_Product();
        $idSale =  $salePost['num'];
        $sale = $salePost[$idSale];
//        echo "<pre>";print_r($sale);die;

        $errors = array();
       
        if (false !== $sale) {
            
            $newSale = $sale;
            if (null == $newSale['created_date']) {
                unset($newSale['created_date']);
            } else {
                $tmp = explode('/', $newSale['created_date']);
                $newSale['created_date'] = mktime(0, 0, 0, $tmp[1], $tmp[0], $tmp[2]);
            }
                
             try {
                /**                
                 * Update
                 */
                $oldSale = $objSale->getSaleById($idSale);
//                echo "<pre>";print_r($newSale);die;
                $objSale->update($newSale, array('sale_id=?' => $idSale));
                
                $product = $objProduct->getProductById($oldSale['product_id']);
//                echo "<pre>";print_r($product);die;
                if($newSale['soluong']){
                    
                    $product['store'] = $product['store'] + $oldSale['soluong'] - $newSale['soluong'];
                    unset($product['unit_name']);
                    $objProduct->update($product, array('product_id=?'=> $product['product_id']));
//                    echo "<pre>";print_r($product);die;
                }
                
                /**
                 * Message
                 */
                $this->session->productMessage =  array(
                           'success' => true,
                           'message' => 'Thông tin bán hàng cập nhật thành công.'
                        );
                
                $this->_redirect('product/admin/select/id/'.$oldSale['product_id']);
            } catch (Exception $e) {
                $errors = array('main' => Nine_Language::translate('Không thể cập nhật thông tin nhập hàng'));
            }
            
                
                
                    
        }
        /*
         * end edit input
         */
    }
    
    
    public function newProductAction()
    {
        $objProduct = new Models_Product();
        /**
         * Check permission
         */
        if (false == $this->checkPermission('new_product', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
//        echo "<pre>";print_r($_POST);die;
        
        
        $data = $this->_getParam('data', false);
        
      
        
        $errors = array();
        $objUnit = new Models_Unit();
        $objInput = new Models_Input();
        $all = $objUnit->getAll();
        $allUnit = $all->toArray();
        
        if (false !== $data) {
        	
            /**
             * Insert new product
             */
            $newProduct = $data;
            
            if (null == $newProduct['created_date']) {
                unset($newProduct['created_date']);
            } else {
                $tmp = explode('/', $newProduct['created_date']);
                $newProduct['created_date'] = mktime(0, 0, 0, $tmp[1], $tmp[0], $tmp[2]);
            }
            $newProduct['update'] = time();
            
            $search = array(" ");
            $newProduct['input_price'] = str_replace($search, '', $newProduct['input_price']);
            $newProduct['sale_price'] = str_replace($search, '', $newProduct['sale_price']);
        
             $value = $data['unit'];
             $objUnit = new Models_Unit();
             $add['name'] = $value;
             
             if($value){
                $flag = 0;
                $add['name'] = trim($value);
                
				$newProduct['unit'] = $objUnit -> getIdOrInsert($add['name']);
             }
           
            
            try {
                $pgid = $objProduct->insert($newProduct);
                
                /**
                 * Update INPUT table
                 */
                $newInput = array(
                    'product_id' => $pgid,
                    'input_price' => $newProduct['input_price'],
                    'created_date' => time(),
                    'soluong' => $newProduct['store']
                );
                $objInput->insert($newInput);
                
                /**
                 * Message
                 */
                $this->session->productMessage =  array(
                           'success' => true,
                           'message' => 'Sản phẩm đã được tạo.'
                        );
                $this->_redirect('product/admin/manage-product');
            } catch (Exception $e) {
                $errors = array('main' =>'Không thể tạo sản phẩm');
            }
        } else {
        	$name = $this->_getParam('name', false);
        	if(false == $name) {
        		$data = array();
        	} else {
        		$data['title'] = $name;
        	}
        	$objUnit = new Models_Unit();
            $unit = @current($objUnit->find($data['unit'])->toArray());
            $data['unit'] = $unit['name'];
        }
        
        $this->view->allUnits = $allUnit;
        
        /**
         * Prepare for template
         */
        $date = time();
        $date = date('d/m/Y', $date);
        
        $this->view->date = $date;
        $this->view->errors = $errors;
        $this->view->data = $data;
        $this->view->headTitle('Tạo sản phẩm mới');
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
        $this->view->menu = array('product', 'newproduct');
        $this->view->fullPermisison = $this->checkPermission('new_product', null, '*'); 
    }
    

    
    public function editProductAction()
    {
        $objProduct = new Models_Product();
        /**
         * Check permission
         */
        if (false == $this->checkPermission('edit_product', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $id     = $this->_getParam('id', false);
        if (false == $id) {
            $this->_redirect('product/admin/manage-product');
        }
        /**
         * Check permission
         */
        if (false == $this->checkPermission('edit_product', null, '*'))
        {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $data   = $this->_getParam('data', false);
        
        $allProduct = $objProduct->getByColumns(array('product_id=?' => $id))->toArray();
        $objUnit = new Models_Unit();
        $all = $objUnit->getAll();
        $allUnit = $all->toArray();
        
        $errors = array();
        if (false !== $data) {
        	
            /**
             * Insert new product
             */
            $newProduct = $data;
            
            if (null == $newProduct['created_date']) {
                unset($newProduct['created_date']);
            } else {
                $tmp = explode('/', $newProduct['created_date']);
                $newProduct['created_date'] = mktime(0, 0, 0, $tmp[1], $tmp[0], $tmp[2]);
            }
            $newProduct['update'] = time();
            
            $search = array(" ");
            $newProduct['input_price'] = str_replace($search, '', $newProduct['input_price']);
            $newProduct['sale_price'] = str_replace($search, '', $newProduct['sale_price']);
        
             $value = $data['unit'];
             $objUnit = new Models_Unit();
             $add['name'] = $value;
             
             if($value){
                $flag = 0;
                $add['name'] = trim($value);
                
				$newProduct['unit'] = $objUnit -> getIdOrInsert($add['name']);
             }
            
            try {
                /**                
                 * Update
                 */
//            	echo "<pre>";print_r($newProduct);die;
                $objProduct->update($newProduct, array('product_id=?' => $id));
                
                
                /**
                 * Message
                 */
                $this->session->productMessage =  array(
                           'success' => true,
                           'message' => 'Cập nhật thông tin sản phẩm thành công'
                        );
                
                $this->_redirect('product/admin/manage-product');
            } catch (Exception $e) {
                $errors = array('main' => 'Không thể cập nhật thông tin sản phẩm');
            }
        } else {
            /**
             * Get old data
             */
            $data = @reset($allProduct);
            /**
             * Change date
             */
            if (0 != $data['created_date']) {
                 $data['created_date'] = date('d/m/Y', $data['created_date']);
            } else {
                $data['created_date'] = '';
            }
            $objUnit = new Models_Unit();
            $unit = @current($objUnit->find($data['unit'])->toArray());
            $data['unit'] = $unit['name'];
            
            if (false == $data) {
                $this->session->productMessage = array(
                                               'success' => false,
                                               'message' => "Không có sản phẩm này"
                                           );
                $this->_redirect('product/admin/manage-product');
            }
        }
         
        $this->view->allUnits = $allUnit;
        /**
         * Prepare for template
         */
        
        $this->view->errors = $errors;
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
        $this->view->data = $data;
        $this->view->headTitle(Nine_Language::translate('Edit Product'));
        $this->view->menu = array('product','');
        $this->view->fullPermisison = $this->checkPermission('edit_product', null, '*');
        
    }
    
 

public function editInputAction()
    {
       
        
        $id     = $this->_getParam('id', false);     
        
        if (false == $id) {
            $this->_redirect('product/admin/manage-product');
        }
        /**
         * Check permission
         */
        $objInput = new Models_Input();
//        $input = $objInput->getInputById($id);
        if (false == $this->checkPermission('edit_input', null, '*'))
        {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        
        $inputPost = $this->_getParam('input', false);
        $objProduct = new Models_Product();
        $idInput =  $inputPost['num'];
        $input = $inputPost[$idInput];
//        echo "<pre>";print_r($input);die;

        $errors = array();
       
        if (false !== $input) {
            
            $newInput = $input;
            if (null == $newInput['created_date']) {
                unset($newInput['created_date']);
            } else {
                $tmp = explode('/', $newInput['created_date']);
                $newInput['created_date'] = mktime(0, 0, 0, $tmp[1], $tmp[0], $tmp[2]);
            }
                
             try {
                /**                
                 * Update
                 */
                $oldInput = $objInput->getInputById($idInput);
                
                $objInput->update($newInput, array('input_id=?' => $idInput));
                $product = $objProduct->getProductById($oldInput['product_id']);
                
                if($newInput['soluong']){
                    $product['store'] = $product['store'] - $oldInput['soluong'] + $newInput['soluong'];
                    unset($product['unit_name']);
                    $objProduct->update($product, array('product_id=?'=> $product['product_id']));
//                    echo "<pre>";print_r($product);die;
                }
                
                /**
                 * Message
                 */
                $this->session->productMessage =  array(
                           'success' => true,
                           'message' => 'Thông tin nhập hàng cập nhật thành công.'
                        );
//                echo "<pre>";print_r($input);die;
                $this->_redirect('product/admin/select/id/'.$oldInput['product_id']);
            } catch (Exception $e) {
                $errors = array('main' => Nine_Language::translate('Không thể cập nhật thông tin nhập hàng'));
            }
            
                
                
                    
        }
        /*
         * end edit input
         */
    }

    
    public function deleteProductAction()
    {
        $objProduct = new Models_Product();
        /**
         * Check permission
         */
        if (false == $this->checkPermission('delete_product')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $gid = $this->_getParam('id', false);
//        echo "<pre>";print_r($gid);die;
        
        if (false == $gid) {
            $this->_redirect('product/admin/manage-product');
        }
        
        $gids = explode('_', trim($gid, '_'));
        
        try {
            foreach ($gids as $gid) {
            	$objProduct->delete(array('product_id=?' => $gid));
            }
            $this->session->productMessage = array(
                                               'success' => true,
                                               'message' => 'Sản phẩm đã được xóa'
                                           );
        } catch (Exception $e) {
            $this->session->productMessage = array(
                                               'success' => false,
                                               'message' => 'Sản phẩm này không thể xóa.Vui lòng thửu lại!'
                                           );
        }
        $this->_redirect('product/admin/manage-product');
    }
    
public function deleteInputAction()
    {
        $objInput = new Models_Input();
        /**
         * Check permission
         */
        if (false == $this->checkPermission('delete_input')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $id = $this->_getParam('id', false);
//        echo "<pre>";print_r($gid);die;
        $objInput = new Models_Input();
        $objProduct = new Models_Product();
        $input = $objInput->getInputById($id);
//        echo "<pre>";print_r($input);die;
        
        if (false == $id) {
            $this->_redirect('product/admin/select/id/'.$input['product_id']);
        }
        
        $ids = explode('_', trim($id, '_'));
        
        try {
            foreach ($ids as $id) {
                
                $inputs = $objInput->getInputById($id);
                $product = $objProduct->getProductById($inputs['product_id']);
                $product['store'] = $product['store'] - $inputs['soluong'];
                $objProduct->update($product, array('product_id=?'=> $inputs['product_id']));
                $objInput->delete(array('input_id=?' => $id));
            }
            $this->session->productMessage = array(
                                               'success' => true,
                                               'message' => 'Thông tin nhập hàng đã được xóa'
                                           );
        } catch (Exception $e) {
            $this->session->productMessage = array(
                                               'success' => false,
                                               'message' => 'Không thể xóa.Vui lòng thử lại!'
                                           );
        }
        $this->_redirect('product/admin/select/id/'.$input['product_id']);
    }
    
    public function deleteSaleAction()
    {
        $objSale = new Models_Sale();
        /**
         * Check permission
         */
        if (false == $this->checkPermission('delete_sale')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $id = $this->_getParam('id', false);
        $objSale = new Models_Sale();
        $objProduct = new Models_Product();
        $sale = $objSale->getSaleById($id);
//        echo "<pre>";print_r($gid);die;
        
        if (false == $id) {
            $this->_redirect('product/admin/select/id/'.$sale['product_id']);
        }
        
        $ids = explode('_', trim($id, '_'));
        
        try {
            foreach ($ids as $id) {
                 
                $sales = $objSale->getSaleById($id);
                $product = $objProduct->getProductById($sales['product_id']);
                $product['store'] = $product['store'] + $sales['soluong'];
                $objProduct->update($product, array('product_id=?' => $sales['product_id']));
//                echo "<pre>";print_r($id);die;
                $objSale->delete(array('sale_id=?' => $id));
            }
            $this->session->selectMessage = array(
                                               'success' => true,
                                               'message' => 'Thông tin bán hàng đã được xóa'
                                           );
        } catch (Exception $e) {
            $this->session->selectMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate('Can NOT delete this sale. Please try again')
                                           );
        }
        $this->_redirect('product/admin/select/id/'.$sale['product_id']);
        
    }
    
    
     public function addInputAction()
    {
         $value = $this->_getParam('value', false);
         $objUnit = new Models_Unit();
         $data['name'] = $value;
         if($data['name']){
         	$id = $objUnit->insert($data);
            $this->setLayout('default');
            $this->view->id = $id;
         }
         
    }
    
    public function inputAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('new_input', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        $data = $this->_getParam('data', false);
        $pro = $this->_getParam('product', false);
        $id = $this->_getParam('id', false);
        $objProduct = new Models_Product();
        $product = $objProduct->getProductById($id);
        $this->view->product = $product;
        
        $objInput = new Models_Input();
        $objUnit = new Models_Unit();
        $allUnit = $objUnit->getAll();
        
        $errors = array();
//        echo "<pre>";print_r($data);die;
        if (false !== $data) {
            /**
             * Insert new category
             */
            $newInput = $data;
            $newInput['created_date'] = time();
            $newInput['product_id'] = $id;
            
            
            
        
            try {
//        	echo "<pre>";print_r($newInput);die;
                $objInput->insert($newInput);
                $product['store'] = $product['store'] + $newInput['soluong'];
                $product['title'] = $pro['title'];
//                echo "<pre>";print_r($product);die;
//die;
                $objProduct->update($product, array('product_id =?' =>  $id));
//                die;
                
                /**
                 * Message
                 */
                $this->session->inputMessage =  array(
                           'success' => true,
                           'message' => 'Thông tin nhập hàng đã được tạo.'
                        );
                
                $this->_redirect('product/admin/manage-product');
            } catch (Exception $e) {
                $errors = array('main' => 'Không thể tạo thông tin nhập hàng.Vui lòng thử lại!');
            }
        } else {
        }
        /**
         * Prepare for template
         */
        $date = time();
        $date = date('d/m/Y', $date);
        
        $this->view->date = $date;
        $this->view->errors = $errors;
        $this->view->data = $data;
        $this->view->allUnits = $allUnit;
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
        $this->view->headTitle(Nine_Language::translate('New Category'));
        $this->view->menu = array('product', 'newproductcategory');
        $this->view->fullPermisison = $this->checkPermission('new_category', null, '*'); 
    }
    
    
    public function saleAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('new_sale', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $data = $this->_getParam('data', false);
        $id = $this->_getParam('id', false);
        $objProduct = new Models_Product();
        $product = $objProduct->getProductById($id);
        $this->view->product = $product;
        
        $objSale = new Models_Sale();
         $objUnit = new Models_Unit();
        $allUnit = $objUnit->getAll();
        
        $errors = array();
        if (false !== $data) {
            /**
             * Insert new category
             */
            $newSale = $data;
            $newSale['created_date'] = time();
            $newSale['product_id'] = $id;
            
            
            
        
            try {
                 $objSale->insert($newSale);
                $product['store'] = $product['store'] - $newSale['soluong'];
                $objProduct->update($product, array('product_id=?'  =>  $id));
                
                /**
                 * Message
                 */
                $this->session->categoryMessage =  array(
                           'success' => true,
                           'message' => 'Thông tin bán hàng đã được tạo.'
                        );
                
                $this->_redirect('product/admin/manage-product');
            } catch (Exception $e) {
                $errors = array('main' => 'Không thể tạo thông tin bán hàng.Vui lòng thử lại!');
            }
        } else {
        }
        /**
         * Prepare for template
         */
        
        $date = time();
        $date = date('d/m/Y', $date);
        
        $this->view->date = $date;
        $this->view->allUnits = $allUnit;
        $this->view->errors = $errors;
        $this->view->data = $data;
        $this->view->headTitle(Nine_Language::translate('New Category'));
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
        $this->view->menu = array('product', 'newproductcategory');
        $this->view->fullPermisison = $this->checkPermission('new_category', null, '*'); 
    }
    
}